#include "channel_map.h"
#include <assert.h>

// 扩容
int map_make_space(struct channel_map *map, int slot, int msize)
{
    if (map->entries <= slot)
    {
        int nentries = map->entries ? map->entries : 32; // 默认32
        void **tmp;

        while (nentries <= slot)
        {
            // 扩大2倍
            nentries <<= 1;
        }

        // 重开辟内存
        tmp = (void **)realloc(map->entries, nentries * msize);
        if (!tmp)
        {
            return -1;
        }
        // 前面的 nentries 项不动，后面的内存全部置 0
        memset(&tmp[map->nentries], 0, (nentries - map->nentries) * msize);
        map->nentries = nentries;
        map->entries = tmp;
    }

    return 0;
}

// 初始化
void map_init(struct channel_map *map)
{
    map->nentries = 0;
    map->entries = NULL;
}

// 清理
void map_clear(struct channel_map *map)
{
    if (map->entries != NULL)
    {
        int i;
        for (i = 0; i < map->nentries; i++)
        {
            if (map->entries[i] != NULL)
            {
                free(map->entries[i]); //free
            }
        }
        free(map->entries);
        map->entries = NULL;
    }
    map->nentries = 0;
}
